import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { WorldManager } from '@/world/WorldManager';

/**
 * 末影珍珠实体 - 可以被投掷并传送玩家
 */
export class EnderPearl {
  private mesh!: THREE.Mesh;
  private position: Vec3;
  private velocity: Vec3;
  private worldManager: WorldManager;
  private onTeleport?: (position: Vec3) => void;
  private age = 0;
  private maxAge = 10; // 10秒后自动消失

  constructor(startPosition: Vec3, direction: Vec3, worldManager: WorldManager) {
    this.position = { ...startPosition };
    this.velocity = {
      x: direction.x * 15, // 投掷速度
      y: direction.y * 15 + 5, // 向上的初始速度
      z: direction.z * 15
    };
    this.worldManager = worldManager;
    
    this.createMesh();
  }

  private createMesh(): void {
    // 创建末影珍珠的外观（紫色发光球体）
    const geometry = new THREE.SphereGeometry(0.1, 8, 8);
    const material = new THREE.MeshBasicMaterial({
      color: 0x8A2BE2, // 紫色
      transparent: true,
      opacity: 0.8
    });
    
    this.mesh = new THREE.Mesh(geometry, material);
    this.mesh.position.set(this.position.x, this.position.y, this.position.z);
    
    // 添加发光效果
    const glowGeometry = new THREE.SphereGeometry(0.15, 8, 8);
    const glowMaterial = new THREE.MeshBasicMaterial({
      color: 0x8A2BE2,
      transparent: true,
      opacity: 0.2
    });
    const glow = new THREE.Mesh(glowGeometry, glowMaterial);
    this.mesh.add(glow);
  }

  public getMesh(): THREE.Mesh {
    return this.mesh;
  }

  public update(deltaTime: number): boolean {
    this.age += deltaTime;
    
    // 如果存在时间过长，自动消失
    if (this.age > this.maxAge) {
      return false;
    }

    // 应用重力
    this.velocity.y -= 9.8 * deltaTime;

    // 更新位置
    this.position.x += this.velocity.x * deltaTime;
    this.position.y += this.velocity.y * deltaTime;
    this.position.z += this.velocity.z * deltaTime;

    // 检查碰撞
    const blockPos = {
      x: Math.floor(this.position.x),
      y: Math.floor(this.position.y),
      z: Math.floor(this.position.z)
    };

    const blockType = this.worldManager.getBlock(blockPos);
    
    // 如果撞到方块或落地，触发传送
    if (blockType > 0 || this.position.y <= 0) {
      this.triggerTeleport();
      return false;
    }

    // 更新网格位置
    this.mesh.position.set(this.position.x, this.position.y, this.position.z);
    
    // 添加旋转动画
    this.mesh.rotation.x += deltaTime * 2;
    this.mesh.rotation.y += deltaTime * 3;

    return true;
  }

  private triggerTeleport(): void {
    // 找到安全的传送位置
    const teleportPos = this.findSafeTeleportPosition();
    
    if (teleportPos && this.onTeleport) {
      // 创建传送效果
      this.createTeleportEffect(teleportPos);
      
      // 触发传送回调
      this.onTeleport(teleportPos);
      
      console.log(`Ender Pearl teleported player to (${teleportPos.x.toFixed(1)}, ${teleportPos.y.toFixed(1)}, ${teleportPos.z.toFixed(1)})`);
    }
  }

  private findSafeTeleportPosition(): Vec3 | null {
    // 从末影珍珠位置开始，向上寻找安全位置
    let safeY = Math.floor(this.position.y);
    
    // 向上搜索，找到第一个有2格高空间的位置
    for (let y = safeY; y <= safeY + 10; y++) {
      const pos1 = { x: Math.floor(this.position.x), y, z: Math.floor(this.position.z) };
      const pos2 = { x: Math.floor(this.position.x), y: y + 1, z: Math.floor(this.position.z) };
      const groundPos = { x: Math.floor(this.position.x), y: y - 1, z: Math.floor(this.position.z) };
      
      const block1 = this.worldManager.getBlock(pos1);
      const block2 = this.worldManager.getBlock(pos2);
      const groundBlock = this.worldManager.getBlock(groundPos);
      
      // 检查是否有足够空间且脚下有支撑
      if (block1 === 0 && block2 === 0 && groundBlock > 0) {
        return { x: this.position.x, y, z: this.position.z };
      }
    }

    // 如果找不到安全位置，返回当前位置
    return { x: this.position.x, y: Math.max(1, this.position.y), z: this.position.z };
  }

  private createTeleportEffect(position: Vec3): void {
    // 创建传送粒子效果
    if (this.mesh.parent) {
      const particleCount = 30;
      for (let i = 0; i < particleCount; i++) {
        const particle = new THREE.Mesh(
          new THREE.SphereGeometry(0.03),
          new THREE.MeshBasicMaterial({
            color: 0x8A2BE2,
            transparent: true,
            opacity: 0.8
          })
        );
        
        particle.position.set(
          position.x + (Math.random() - 0.5) * 3,
          position.y + Math.random() * 2,
          position.z + (Math.random() - 0.5) * 3
        );
        
        this.mesh.parent.add(particle);
        
        // 粒子动画
        const startTime = Date.now();
        const animate = () => {
          const elapsed = Date.now() - startTime;
          if (elapsed > 1500) {
            if (particle.parent) {
              particle.parent.remove(particle);
            }
            return;
          }
          
          particle.position.y += 0.03;
          particle.material.opacity = 0.8 * (1 - elapsed / 1500);
          particle.scale.multiplyScalar(1.02);
          requestAnimationFrame(animate);
        };
        animate();
      }
    }
  }

  public setTeleportCallback(callback: (position: Vec3) => void): void {
    this.onTeleport = callback;
  }

  public dispose(): void {
    if (this.mesh) {
      if (this.mesh.parent) {
        this.mesh.parent.remove(this.mesh);
      }
      
      this.mesh.geometry.dispose();
      if (Array.isArray(this.mesh.material)) {
        this.mesh.material.forEach(mat => mat.dispose());
      } else {
        this.mesh.material.dispose();
      }
    }
  }
}